﻿using System.Text.Json;

namespace MicroBlog
{
    /// <summary>
    /// Session扩展，使用Session可以存取可序列化的对象
    /// </summary>
    public static class SessionExtensions
    {
        /// <summary>
        /// 将可序列化对象保存到Session中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonSerializer.Serialize(value));
        }
        /// <summary>
        /// 从Session中获取一个可序列化的对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T? Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default : JsonSerializer.Deserialize<T>(value);
        }
    }
}
